package com.lzf.provider;

import com.lzf.domain.Users;
import com.lzf.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UsersService usersService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = null;
        User u = null;
        if(username != null && username != "") {
            //可自定义实现RBAC 等模型，
            users = usersService.selectByUsername(username);

            if(users != null){
                List<GrantedAuthority> list = new ArrayList<>();

                //角色，ROLE_
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_" + users.getRole());
                list.add(grantedAuthority);

                //创建 security 的 User
                u = new User(users.getUsername(),users.getPassword(),list);
            }

        }
        return u;
    }
}
